﻿using System.Collections.Generic;
using System.Linq;
using Castle.Facilities.NHibernateIntegration;
using Castle.Services.Transaction;
using NHibernate;
using NHibernate.Linq;


namespace LeoMVC.Repository
{
    public class NHibernateRepository<TKey,TEntity>:IRepository<TKey,TEntity>
        where TKey:global::System.IComparable
    {
        private readonly ISessionManager _sessionManager;

        public NHibernateRepository(ISessionManager sessionManager)
        {
            this._sessionManager = sessionManager;
        } 

        protected internal virtual ISession Session
        {
             get { return _sessionManager.OpenSession(); }
        }

        [Transaction(TransactionMode.Requires)]
        public void Save(TEntity item)
        {
            Session.Save(item);
        }

        public IEnumerable<TEntity> FindAll()
        {
            return Session.CreateCriteria(typeof (TEntity)).Future<TEntity>();
        }

        public IEnumerable<TEntity> FindBy(params TKey[] keys)
        {
            throw new System.NotImplementedException();
        }

        public TEntity FindBy(TKey key)
        {
            return Session.Get<TEntity>(key);
        }

        [Transaction(TransactionMode.Requires)]
        public void Delete(TEntity item)
        {
            Session.Delete(item);
        }

        [Transaction(TransactionMode.Requires)]
        public void SaveOrUpdate(TEntity item)
        {
            Session.SaveOrUpdate(item);
        }

        [Transaction(TransactionMode.Requires)]
        public void Update(TEntity item)
        {
            Session.Update(item);
        }
    }
}
